package com.scaffold.myproject.entity;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用基础实体类（使用 FastJSON 2）
 */
@Getter
@Setter
@Slf4j
@FieldDefaults(level = lombok.AccessLevel.PRIVATE)
public abstract class BaseDO implements Serializable {

    @TableField(value = "deleted", fill = FieldFill.INSERT)
    Boolean deleted = false;

    @TableField(value = "id", fill = FieldFill.INSERT)
    Long id;

    @TableField(value = "created_time", fill = FieldFill.INSERT)
    LocalDateTime createdTime;

    @TableField(value = "modified_time", fill = FieldFill.INSERT_UPDATE)
    LocalDateTime modifiedTime;

    @TableField("istest")
    Boolean istest;

    @TableField("attributes")
    String attributes;

    /**
     * 将 attributes 字段从 JSON 转换为 Map<String, Object>
     */
    public Map<String, Object> attr2Map() {
        try {
            if (attributes == null || attributes.trim().isEmpty()) {
                return new HashMap<>();
            }
            return JSON.parseObject(attributes, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.error("attr2Map 解析失败: {}", attributes, e);
            return new HashMap<>();
        }
    }

    /**
     * 将 Map<String, Object> 转为 JSON 字符串存入 attributes 字段
     */
    public void saveMap2Attr(Map<String, Object> map) {
        try {
            this.attributes = JSON.toJSONString(map);
        } catch (Exception e) {
            log.error("saveMap2Attr 序列化失败", e);
        }
    }
}
